package designpattern.prototype;

import java.io.*;

public class Person implements Serializable,Cloneable {
    public static final long serialVersionUID = 1534213213;

    private String name;
    private int age;
    private Toy toy;

    public Person() {
    }

    public Person(String name, int age, Toy toy) {
        this.name = name;
        this.age = age;
        this.toy = toy;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Toy getToy() {
        return toy;
    }

    public void setToy(Toy toy) {
        this.toy = toy;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", toy=" + toy +
                '}';
    }

    //深层复制  1使用clone方法来实现
    @Override
    protected Person clone() throws CloneNotSupportedException {
        Person person = (Person)super.clone();
        Toy toy = person.getToy();
        person.setToy(toy.clone());
        return person;
    }

    //深层复制  2使用对象序列化来实现
    public Person clone2(){
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        Person copyObj = null;
        try {
            //将对象序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //将对象反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            copyObj =(Person) ois.readObject();
        }catch (Exception e){
        }finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return copyObj;
    }
}
